//
//  WeeX_Vc.swift
//  Eddard
//
//  Created by eme on 2017/3/22.
//  Copyright © 2017年 seongbrave. All rights reserved.
//

import UIKit
import RxSwift
import RxCocoa
import UtilCore
import WeexSDK



class WeeX_Vc: UIViewController {
    var disposeBag = DisposeBag()
    var instance:WXSDKInstance?;
    var weexView = UIView()
    var weexHeight:CGFloat?;
    var top:CGFloat?;
    var url:String?;
    lazy var leftBtn: UIButton = {
        let button = UIButton()
        button.frame = CGRect(x: 0, y: 0, width: 30, height: 30)
        button.setImage(UIImage(named: "reload"), for: .normal)
        return button
    }()
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.clipsToBounds = true
        
        if !self.navigationController!.navigationBar.isHidden {
            top = self.navigationController!.navigationBar.frame.maxY;
        } else {
            top = UIApplication.shared.statusBarFrame.maxY
        }
        weexHeight = self.view.frame.size.height - top! - 49
        render()
        bindToViewModel()
        customLeftBarButtonItem()
    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.updateInstanceState(.WeexInstanceAppear)
    }
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        self.updateInstanceState(.WeexInstanceDisappear)
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    override func viewDidLayoutSubviews() {
//        weexHeight = self.view.frame.size.height
    }
    deinit {
        if instance != nil {
            instance!.destroy()
        }
    }
    
    func render(){
        if instance != nil {
            instance!.destroy()
        }
        instance = WXSDKInstance();
        instance!.viewController = self
        let width = self.view.frame.size.width
        
        instance!.frame = CGRect(x: self.view.frame.size.width-width, y: top!, width: width, height: weexHeight!)
        weak var weakSelf:WeeX_Vc? = self
        instance!.onCreate = { view -> Void in
            weakSelf!.weexView.removeFromSuperview()
            weakSelf!.weexView = view!;
            weakSelf!.view.addSubview(self.weexView)
            UIAccessibilityPostNotification(UIAccessibilityScreenChangedNotification, weakSelf!.weexView)
            
        }
        instance!.onFailed = {
            error -> Void in
            if let error = error{
                print( error)
            }
        }
        
        instance!.renderFinish = {[unowned self]
            view -> Void in
            self.updateInstanceState(.WeexInstanceAppear)
            print("render finish")
        }
        instance!.updateFinish = {
            view  -> Void in
            
        }
        instance!.render( with: NSURL( string: "\(self.url!)?random=\(arc4random())" ) as URL!, options: ["bundleUrl":self.url!], data: nil)
        
    }
    /**
     自定义leftBarButtonItem
     */
    func customLeftBarButtonItem()  {
        
        let leftItem = [UIBarButtonItem(image: UIImage(named: "reload"), style: .plain, target: self, action: #selector(reloadClick)),UIBarButtonItem(image: UIImage(named: "scan"), style: .plain, target: self, action: #selector(scanClick))]
        self.navigationItem.rightBarButtonItems = leftItem
        if let navVc = self.navigationController {
            if navVc.viewControllers.count > 1{
                self.navigationItem.leftBarButtonItem = UIBarButtonItem(image: UIImage(named: "iconfont-back"), style: .plain, target: self, action: #selector(backToView))
            }
        }
        
    }

    func updateInstanceState(_ state:WXState) -> Void {
        if let instance = self.instance , instance.state != state {
            instance.state = state
            if state == .WeexInstanceAppear {
                WXSDKManager.bridgeMgr().fireEvent(instance.instanceId, ref: "_root", type: "viewappear", params: ["aaa":"bbbbviewappear"], domChanges: nil)
            }else if state == .WeexInstanceDisappear {
                WXSDKManager.bridgeMgr().fireEvent(instance.instanceId, ref: "_root", type: "viewdisappear", params: ["aaa":"bbbbbviewdisappear"], domChanges: nil)
            }
        }

    }
    /**
     重新加载
     */
    func reloadClick()  {
        self.render()
    }
    /**
     扫一扫
     */
    func scanClick()  {
        let scanVc = UtilCore.scanVc
        scanVc.didScanValue_Block = { relValue in
            if relValue.hasPrefix("http://") || relValue.hasPrefix("https://"){
                if relValue.hasSuffix(".js"){
                    _ = "weexvc".openURL(["url":relValue])
                }else{
                    _ = relValue.openURL()
                }
            }else{
                self.view.toast(relValue)
            }
        }
        self.navigationController?.pushViewController(scanVc, animated: true)
    }
    /**
     自定义返回上级界面
     */
    func backToView()  {
        _ = navigationController?.popViewController(animated: true)
    }
    
}

extension WeeX_Vc{
    /**
     绑定到viewmodel 设置
     */
    func bindToViewModel(){
        
        self.leftBtn.rx.tap.subscribe(onNext: { [unowned self] in
            self.render()
            
            ///暂时vue 还不支持fireGlobalEvent事件了
            self.instance?.fireGlobalEvent("testttt", params: ["aa":"bb"])
        }).addDisposableTo(disposeBag)
        
        
    }
    
    
}
